<template>
  <div class="pagination">
    <button 
        :disabled="pageNo === 1 "
        @click="$emit('newPage' , pageNo - 1)"
    >上一页</button>

    <button
        :class="{active: pageNo === 1 }"
        @click="$emit('newPage' , 1)"
        v-show="startEnePage.start > 1 "
    >1</button>

    <button v-show="startEnePage.start > 2 ">···</button>

    <button
        v-for="page in startEndArr" :key="page"
        :class="{active: pageNo === page}"
        @click="$emit('newPage' , page)"
    >{{page}}</button>

    <button
        v-show="startEnePage.end < totalPages - 1 "
    >···</button>

    <button
        :class="{active: pageNo === totalPages }"
        @click="$emit('newPage' , totalPages)"
        v-show="startEnePage.end <  totalPages"
    >{{totalPages}}</button>

    <button
        :disabled="pageNo === totalPages "
        @click="$emit('newPage' , pageNo + 1)"
    >下一页</button>

    <button style="margin-left: 30px">共 {{total}} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["pageNo" , "totalPages" , "continuepage" , "total"],
  
  computed:{
    //计算要遍历的数字
    startEndArr(){
        let arr = []
        for(let i = 1 ; i <= this.startEnePage.end ; i++){
            if(i >= this.startEnePage.start){
                arr.push(i)
            }
        }
        return arr
    },

    //计算初始页和结束页
    startEnePage(){
        const {pageNo , totalPages , continuepage} = this
        let start,end = ""

        //如果小总页树于连续页
        if(totalPages <= continuepage){
            start = 1,
            end = totalPages
        }else{
            start = pageNo - (continuepage-1)/2
            end = pageNo + (continuepage-1)/2

            //如果起始页小于1
            if(start < 1){
                start = 1,
                end = continuepage
            }

            //如果结束页大于总页树
            if(end > totalPages){
                end = totalPages
                start = totalPages - continuepage + 1
            }
        }

        return {start , end}
    }
  },

};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>